<template>
    <div>
        <el-upload action='http://qikuaiban.oss-cn-hangzhou.aliyuncs.com' :data='dataObj' :multiple='false'
            :file-list='fileList' :before-upload='beforeUpload' :on-remove='handleRemove'
            :on-success='handleUploadSuccess' :on-preview='handlePreview'>
            <el-button size='small' type='primary'>点击上传</el-button>
            <div slot='tip' class='el-upload__tip'>只能上传doc/docx文件，且不超过10MB</div>
        </el-upload>
    </div>
</template>
<script>
    import { policy } from './policy'
    import { getUUID } from '@/utils'

    export default {
        name: 'singleUpload',
        props: {
            value: String
        },
        data() {
            return {
                dataObj: {
                    policy: '',
                    signature: '',
                    key: '',
                    ossaccessKeyId: '',
                    dir: '',
                    host: ''
                    // callback:'',
                },
                fileList: []
            }
        },
        methods: {
            reset() {
                this.fileList.pop()
            },
            change(fileName, fileUrl) {
                this.fileList.push({ name: fileName, url: fileUrl })
            },
            handleRemove(file, fileList) {
                this.emitInput('')
            },
            handlePreview(file) {
                // 点击下载
                this.getBlob(file.url).then(res => {
                    this.saveAs(res, file.name)
                })
            },
            getBlob(url) { // url:是文件在oss上的地址
                return new Promise(resolve => {
                    const xhr = new XMLHttpRequest()
                    xhr.open('GET', url, true)
                    xhr.responseType = 'blob'// 请求类型是blob类型
                    xhr.crossOrigin = '*' // 解决跨域问题
                    xhr.onload = () => {
                        if (xhr.status === 200) {
                            resolve(xhr.response)
                        }
                    }
                    xhr.send()
                })
            },
            saveAs(blob, filename) {
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, filename)
                } else {
                    const link = document.createElement('a')
                    const body = document.querySelector('body')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = filename
                    link.style.display = 'none'
                    body.appendChild(link)
                    link.click()
                    body.removeChild(link)
                    window.URL.revokeObjectURL(link.href)
                }
            },
            beforeUpload(file) {
                let _self = this

                var fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
                const isFile = fileType === 'doc' || fileType === 'docx'
                if (!isFile) {
                    this.$message.error('请选择正确的文件格式')
                    return false
                }

                const isLt50M = file.size / 1024 / 1024 < 10
                if (!isLt50M) {
                    this.$message.error('上传文件大小不能超过 10MB!')
                    return false
                }

                return new Promise((resolve, reject) => {
                    policy().then(response => {
                        _self.dataObj.policy = response.data.policy
                        _self.dataObj.signature = response.data.signature
                        _self.dataObj.ossaccessKeyId = response.data.accessid
                        // eslint-disable-next-line no-template-curly-in-string
                        _self.dataObj.key = response.data.dir + '/' + getUUID() + '_${filename}'
                        _self.dataObj.dir = response.data.dir
                        _self.dataObj.host = response.data.host
                        resolve(true)
                    }).catch(err => {
                        reject(new Error(false))
                        console.log(err)
                    })
                })
            },
            handleUploadSuccess(res, file) {
                console.log('上传成功...')
                this.fileList.pop()
                // eslint-disable-next-line no-template-curly-in-string
                this.fileList.push({ name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name) })
                this.$emit('change', this.fileList[0].url, this.fileList[0].name)
            }
        }
    }
</script>
<style>

</style>